package com.hle;

import java.util.ArrayList;
import java.util.List;

public class Queues {
	
	int[] cols;
	int ways;
	List<List<String>> list;

	public static void main(String[] args) {
		new Queues().queue(4);
	}
	
	void place(int row) {
		if (row == cols.length) {
			ways++;
			show();
			return;
		}
	
		for (int col = 0 ; col < cols.length; col ++) {
			if (isAvailable(col, row)) {
				cols[row] = col;
				place(row + 1);
			}
		}
	}
	
	void queue(int n ) {
		list = new ArrayList<>();
		cols = new int[n];
		place(0);
		System.out.println(ways);
		System.out.println(list);
	}
	
	boolean isValid(int row, int col) {
		for (int i = 0; i < row; i++) {
			// 第col列已经有皇后
			if (cols[i] == col) {
				System.out.println("[" + row + "][" + col + "]=false");
				return false;
			}
			// 第i行的皇后跟第row行第col列格子处在同一斜线上
			if (row - i == Math.abs(col - cols[i])) {
				System.out.println("[" + row + "][" + col + "]=false");
				return false;
			}
		}
		System.out.println("[" + row + "][" + col + "]=true");
		return true;
	}
	
	boolean isAvailable(int col, int row) {
		for (int i = 0; i < row; i++) {
			// 第col列已经有皇后
			if (cols[i] == col) {
//				System.out.println("[" + row + "][" + col + "]=false");
				return false;
			}
			// 第i行的皇后跟第row行第col列格子处在同一斜线上
			if (row - i == Math.abs(col - cols[i])) {
//				System.out.println("[" + row + "][" + col + "]=false");
				return false;
			}
		}
//		System.out.println("[" + row + "][" + col + "]=true");
		return true;
	}
	
	void show() {
		List<String> stringList = new ArrayList<>();
		list.add(stringList);
		for (int row = 0; row < cols.length; row++) {
			StringBuffer buffer = new StringBuffer();
			for (int col = 0; col < cols.length; col++) {
				if (cols[row] == col) {
//					System.out.print("1 ");
					buffer.append("Q");
				}else {
//					System.out.print("0 ");
					buffer.append(".");
				}
			}
			stringList.add(buffer.toString());
//			System.out.println();
		}
	}
}
